package com.aisb.login;

import com.aisb.core.InitParam;
import com.aisb.core.Result;
import com.aisb.core.SessionBean;
import com.aisb.core.util.DateUtil;
import com.aisb.core.util.RequestUtil;
import com.aisb.core.log.LogLogin;
import com.aisb.core.log.LogVisit;
import com.aisb.manage.AuthService;
import com.aisb.manage.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController {

    @Autowired
    LoginDao loginDao;

    @Autowired
    AuthService authService;

    @Autowired
    UserService userService;

    @RequestMapping(value = {"/", "/login"})
    public String index(Model model) {
        return "login/login";
    }

    @RequestMapping(value = "/loginout")
    public String loginout(Model model) {
        return "login/loginout";
    }

    @RequestMapping(value = "/login/in")
    @ResponseBody
    @LogLogin("登录系统")
    public Result login(@RequestParam Map param, HttpServletRequest httpServletRequest, HttpSession httpSession) {
        String userId = (String) param.get("userId");
        String userPwd = (String) param.get("userPwd");

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                userId, userPwd);

        String msg = "";
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken); // 完成登录
            SessionBean sessionBean = (SessionBean) subject.getPrincipal();

            String ip = RequestUtil.getIpAddress(httpServletRequest);
            String ipAddress = RequestUtil.getAddressByIP(ip);
            sessionBean.setIp(ip);
            sessionBean.setIpAddress(ipAddress);
            if (StringUtils.isBlank(sessionBean.getUserTheme())) {// 设置默认主题
                sessionBean.setUserTheme(InitParam.DEFAULT_THEME);
            }

            // 查询用户角色，判断是否为超级管理员
            List<Map> roles = authService.rolesForUser(param);
            for (Map r : roles) {
                String roleId = (String) r.get("roleId");
                if (InitParam.ADMIN_JOB_ID.equals(roleId)) {
                    sessionBean.setAdmin(true);
                    break;
                }
            }

            // 记录用户登录时间
            Map modifyInfo = new HashMap();
            modifyInfo.put("userId", userId);
            modifyInfo.put("lastLoginTime", DateUtil.getInstance().getToday(InitParam.FORMAT_TIME));
            userService.userModify(modifyInfo);

            httpSession.setAttribute("userInfo", sessionBean);
        } catch (Exception e) {
            if (e instanceof UnknownAccountException) {
                msg = "登录失败，用户账号不存在！";
            } else if (e instanceof IncorrectCredentialsException) {
                msg = "登录失败，用户密码不正确！";
            } else {
                msg = "登录失败，" + e.getMessage();
            }

            return new Result(false, msg);
        }

        return new Result(true, "");
    }

    @RequestMapping(value = "/4031")
    public String error403(Model model) {
        return "login/403";
    }

    @RequestMapping(value = "/kickout")
    @LogVisit("被踢出系统")
    public String kickout(Model model) {
        return "login/kickout";
    }

}
